# coding: utf-8
import re
from copy import deepcopy

from db.mongo import MongoTest
from test00 import isDrink

food_name_lst = []

def search_limit(p, mongo, price_start, price_end):
    global food_name_lst
    mts = mongo.find_page("anly_data", p)
    page_plan = []
    if len(mts) == 0:
        return False
    for mt in mts:
        shop_id = str(mt.get("shop_id"))
        shop_name = mt.get("shop_name")
        address = mt.get("address")
        location = str(mt.get("latitude")) + "," + str(mt.get("longitude"))
        print(shop_name + "  - 计算满减")
        # 配送费, 正则表达式从字符串获取数字
        if mt.get("shipping_fee_tip") == "免配送费":
            shipping_fee_tip = 0
        else:
            shipping_fee_tip = float(re.findall(r'\d+', mt.get("shipping_fee_tip"))[0])
        # 起送费， 正则表达式从字符串获取数字
        min_price_tip = float(re.findall(r'\d+', mt.get("min_price_tip"))[0])
        trade_area = mt.get("trade_area")
        discounts2 = mt.get("discounts2")
        food_spu_tags = mt.get("food_spu_tags")
        # discounts 满减信息，new_user_reduce_fee 门店新用户立减
        discounts = list()
        new_user_reduce_fee = 0
        for activity in discounts2:
            info = activity.get("info")
            res = re.search(r"满\d+减\d+", info)
            res2 = re.search(r'满\d+减\d+代金券', info)
            res3 = re.search(r'配送费满减', info)
            if res and not res2 and not res3:
                for mj in info.split(";"):
                    allPrice = mj.find("满")
                    reducePrice = mj.find("减")
                    allPrice = mj[allPrice + 1:reducePrice]
                    reducePrice = mj[reducePrice + 1:]

                    discounts.append((float(allPrice), float(reducePrice)))
            elif '本店新用户立减' in info:
                new_user_reduce_fee = float(re.findall(r'\d+', info)[0])
        # 过滤一些满减信息，满减额小于5元的过滤掉，满减后大于20元的过滤掉,如果最终没有符合条件的满减，跳过该店铺
        satisfied_discounts = []
        for discount in discounts:
            reduce_price = discount[1]
            all_price = discount[0]
            satisfied_discounts.append(discount)
        discounts = satisfied_discounts
        if len(discounts) == 0:
            continue
        foods = []
        for food_tag in food_spu_tags:
            # 折扣商品不能享受满减，折扣商品的标记固定为act17, 以及过滤掉价格为0的商品
            if not food_tag.get("tag") == 'act17':
                spus = food_tag.get("spus")
                for food in spus:
                    food_name_lst.append(food.get("name"))
                    if not food.get("skus")[0].get("activity_tag_id","") == "act_17_17" and not food.get("min_price") == 0:
                        foods.append((food.get("name"), food.get("min_price"), food.get("skus")[0].get("box_price")))


        allPrice = discounts[0][0]
        reduce_price = discounts[0][1]
        # 双指针法，i指针指向头部，j指针指向尾部，i向尾部移动，j向头部移动
        i = 0
        j = len(foods) - 1

        actPlan = []
        tempMethods = {"menu" : {}, "new_user_reduce_fee" : new_user_reduce_fee, "all_price" : allPrice, "reduce_price" : reduce_price, "shipping_fee_tip" : shipping_fee_tip, "min_price_tip" : min_price_tip}
        tempPrice = 0
        allPackingFee = 0




        if len(actPlan) == 0:
            continue
        for m in range(len(actPlan)):
            for n in range(m + 1, len(actPlan)):
                if actPlan[m].get("total_price") > actPlan[n].get("total_price"):
                    temp = deepcopy(actPlan[m])
                    actPlan[m] = deepcopy(actPlan[n])
                    actPlan[n] = temp
        page_plan.append({"actPlan" : actPlan, "address" : address, "location" : location, "shopName" : shop_name , "mj": "满" + str(allPrice) + "减" + str(reduce_price), "min_price_tip":min_price_tip})
    return page_plan

if __name__ == '__main__':
    page_count = 0
    mongo = MongoTest()
    plans = list()
    price_start = 10
    price_end = 15
    while True:
        print("==第{}页 =================== 累计：{}".format(page_count + 1, (page_count + 1) * 5))
        res = search_limit(page_count, mongo, price_start, price_end)
        if res == False:
            break
        else:
            plans += res
        page_count += 1

    # 写入txt文件
    with open("mt1126_1.txt", "w", encoding="utf-8") as file:
        for plan in plans:
            file.write("* {}\t[{}]************\n".format(plan.get("shopName"),plan.get("address")))
            file.write("\t[{}]\t[起送费]:{}\n".format(plan.get("mj"), plan.get("min_price_tip")))
            for index, foods in list(enumerate(plan.get("actPlan")))[:10]:
                file.write("\t\t方案{}:\n".format(index + 1))
                file.write("\t\t\t[选择]：")
                for food_name, food_price in foods.get("menu").items():
                    file.write(food_name + ":" + str(food_price) + "；")
                file.write("\n")
                file.write("\t\t\t[总价(含包装费)]:" + str(foods.get("total_price")) + "\t[配送费]:" + str(foods.get("shipping_fee_tip")) + "\t[门店新用户立减]:" + str(foods.get("new_user_reduce_fee")) + "\n")
                file.write("\t\t\t[实付]:" + str(round(foods.get("total_price") + foods.get("shipping_fee_tip") - foods.get("new_user_reduce_fee") - foods.get("reduce_price"),1)) + "\n")
        file.close()


    with open("food_name.txt", "w", encoding="utf-8") as file:
        count = 0
        for name in food_name_lst:
            if count == 10:
                file.write("\n" + name + "\t")
                count = 1
            else:
                file.write(name + "\t")
                count += 1
        file.close()